<template>
  <div>
    <!-- 1.表头 -->
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>文章列表</span>
      </div>
      <!-- 1.2搜索区域 -->
      <div class="search-box">
        <el-form :inline="true" class="demo-form-inline">
          <el-form-item label="文章分类">
            <el-select placeholder="请选择分类" value="" v-model="q.cate_id">
              <el-option
                v-for="item in artList"
                :key="item.id"
                :label="item.cate_name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发布状态">
            <el-select placeholder="选择发布状态" v-model="q.state">
              <el-option label="已发布" value="已发布"></el-option>
              <el-option label="草稿" value="草稿"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="initArtList">筛选</el-button>
            <el-button type="success" @click="doReset">重置</el-button>
          </el-form-item>
        </el-form>
        <!-- 发表文章的按钮 -->
        <el-button
          type="primary"
          size="small"
          class="btn-pub"
          @click="addVisible = true"
          >发表文章</el-button
        >
      </div>
      <!-- 1.2文章表格区域 -->
      <el-table :data="artList" border style="width: 100%">
        <el-table-column label="文章标题">
          <!-- 作用域插槽获取文章id -->
          <template v-slot="obj">
            <el-link type="primary" @click="doDetail(obj.row.id)">{{
              obj.row.title
            }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="cate_name" label="分类"> </el-table-column>
        <el-table-column label="发表时间">
          <!-- 使用作用域插槽获取当前的时间 -->
          <template v-slot="{ row }">
            {{ formatTime(row.pub_date) }}
          </template>
        </el-table-column>
        <el-table-column prop="state" label="状态"> </el-table-column>
        <el-table-column label="操作">
          <template v-slot="obj">
            <el-button type="danger" @click="del(obj.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 1.3分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="q.pagenum"
        :page-sizes="[2, 5, 10, 20]"
        :page-size="q.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 2.发表文章对话框 -->
    <el-dialog title="发表文章" :visible.sync="addVisible" fullscreen>
      <el-form>
        <!-- 2.1标题 -->
        <el-form-item label="文章标题" label-width="80px">
          <el-input placeholder="请输入标题" v-model="addForm.title"></el-input>
        </el-form-item>
        <!-- 2.2文章分类 -->
        <el-form-item label="文章分类" label-width="80px">
          <el-select
            placeholder="请选择分类"
            value=""
            size="small"
            style="width: 100%"
            v-model="addForm.cate_id"
          >
            <el-option
              v-for="item in cateList"
              :key="item.id"
              :label="item.cate_name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 2.3文章内容 -->
        <el-form-item label="文章内容" label-width="80px">
          <quillEditor v-model="addForm.content"></quillEditor>
        </el-form-item>
        <!-- 2.4文章封面 -->
        <el-form-item label="文章封面" label-width="80px">
          <img
            src="@/assets/images/images.jpg"
            alt=""
            width="200px"
            ref="imgRef"
          />
          <br />
          <!-- 文件选择框，默认被隐藏 -->
          <input
            type="file"
            style="display: none"
            accept="image/*"
            ref="iptFile"
            @change="doChange"
          />
          <!-- 选择封面的按钮 -->
          <el-button type="text" @click="$refs.iptFile.click()"
            >+ 选择封面</el-button
          >
        </el-form-item>
        <!-- 2.5 按钮 -->
        <el-form-item label-width="80px">
          <el-button type="primary" @click="addArticle('已发布')"
            >发布</el-button
          >
          <el-button type="success" @click="addArticle('草稿')"
            >存草稿</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 3.文章详情对话框 -->
    <el-dialog title="文章预览" :visible.sync="detailLog" width="80%">
      <h1 >{{ artDetail.title }}</h1>
      <div>
        <span>作者:{{ artDetail.nickname }}</span> 
        <span>发布时间:{{ formatTime(artDetail.pub_date) }}</span> 
        <span>所属分类:{{ artDetail.cate_name }}</span> 
        <span>状态:{{ artDetail.state }}</span> 
      </div>
      <el-divider></el-divider>
      <img
        :src="'http://big-event-vue-api-t.itheima.net' + artDetail.cover_img"
        alt=""
      />
      <div v-html="artDetail.content"></div>
    </el-dialog>
  </div>
</template>

<script>
// 导入富文本编辑插件
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

import moment from 'moment'

import { quillEditor } from 'vue-quill-editor'
export default {
  name: 'ArtList',
  components: { quillEditor },
  //1.数据
  data () {
    return {
      addVisible: false,
      addForm: {
        title: '',
        cate_id: '',
        content: '',
        state: '',
        cover_img: ''
      },
      cateList: [],
      //1.4查询文章列表参数 设置默认参数
      q: {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''
      },
      //1.6 文章总数量
      total: 0,
      //1.5声明空数组接收数据
      artList: [],
      //1.7 文章详情
      artDetail: {},
      //1.8 文章详情对话框
      detailLog: false
    }
  },
  //2.事件和方法
  methods: {
    //2.1表单change事件
    doChange (e) {
      //(1)获取用户选择的封面
      let file = e.target.files[0]
      console.log(file)
      if (file) {
        //(2)绑定到data中
        this.addForm.cover_img = file
        //生成url
        const url = URL.createObjectURL(file)
        //显示到img
        this.$refs.imgRef.src = url
      }
    },
    //2.2 发表文章
    async addArticle (state) {
      //(1)绑定参数
      console.log(state)
      this.addForm.state = state
      //(2)有文件的接口必须要使用：FormData
      const fd = new FormData()
      /* 把data中的数据，添加到FormData中 */
      for (let key in this.addForm) {
        fd.append(key, this.addForm[key])
      }
      //（3）发送ajax，参数是formdata
      const { data: res } = await this.$axios.post('/my/article/add', fd)
      console.log(res)
      //（4）发送成功，弹框消失，刷新文章列表

      if (res.code === 0) {
        this.$message.success(res.message)
        this.addVisible = false
        
        //刷新列表
        this.initArtList()
      }
    },
    //2.3获取文章列表
    async initArtList () {
      const { data: res } = await this.$axios.get('/my/article/list', {
        params: this.q
      })
      console.log(res)
      this.artList = res.data
      this.total = res.total
      /* 假如总共有10条数据，每页2条。此时总页数 10/2=5
      当我们删除2条数据之后，总数变成8，此时真正总页数8/2=4
      此时pagenum还是5，请求不到数据
      判断 如果当前的pagenum 超过总数/每页条数 就需要自减，然后重新请求数据 */
      if (this.q.pagenum>Math.ceil(this.total/this.q.pagesize)) {
        this.q.pagenum--
        this.initArtList()
      }
    },
    //2.4删除文章
    async del (id) {
      //(1)弹出确认框
      const confirm = await this.$confirm(
        '此操作将永久删除该分类, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => {})

      //(2)点击确定发送ajax请求
      if (confirm) {
        const { data: res } = await this.$axios({
          method: 'delete',
          url: '/my/article/info',
          params: { id }
        })
        //删除成功
        if (res.code === 0) {
          this.$message.success('删除分类成功！')
          //重新加载分类列表
          this.initArtList()
        } else {
          this.$message.error(res.message)
        }
      }
    },
    //2.5 过滤时间格式
    formatTime (time) {
      return moment(time).format('YYYY-MM-DD HH:mm:ss')
    },
    //2.6 分页组件页码sise变化
    handleSizeChange (val) {
      // console.log(val);
      //(1)修改每页条数
      this.q.pagesize = val
      //(2)刷新列表
      this.initArtList()
    },
    //2.7分页组件page变化
    handleCurrentChange (page) {
      //  console.log(page);
      //(1)修改每页条数
      this.q.pagenum = page
      //(2)刷新列表
      this.initArtList()
    },
    //2.8 重置功能
    doReset () {
      this.q = {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''
      }
      this.initArtList()
    },
    //2.9 查看文章详细
    async doDetail (id) {
      const { data: res } = await this.$axios.get('/my/article/info', {
        params: { id }
      })
      console.log(res)
      this.artDetail = res.data
      this.detailLog = true
    }
  },
  //3.created
  async created () {
    //3.1请求文章列表
    const { data: res } = await this.$axios.get('/my/cate/list')
    console.log(res)
    //3.2绑定在data中
    this.cateList = res.data
    //3.3加载默认请求刷新
    this.initArtList()
  }
}
</script>

<style lang="less" scoped>
.search-box {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  .btn-pub {
    margin-top: 5px;
  }
}

/deep/ .ql-editor {
  min-height: 300px;
}

// 设置图片封面的宽高
.cover-img {
  width: 400px;
  height: 280px;
  object-fit: cover;
}

.el-pagination {
  margin-top: 15px;
}

.title {
  font-size: 24px;
  text-align: center;
  font-weight: normal;
  color: #000;
  margin: 0 0 10px 0;
}

.info {
  font-size: 12px;
  span {
    margin-right: 20px;
  }
}

// 修改 dialog 内部元素的样式，需要添加样式穿透
/deep/ .detail-box {
  img {
    width: 500px;
  }
}

</style>
